package com.yaolaizaixian.merchant.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.yaolaizaixian.merchant.HomeActivity;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.ShopData;
import com.yaolaizaixian.merchant.bean.ShopDetailsModel;
import com.yaolaizaixian.merchant.bean.ShopListModel;
import com.yaolaizaixian.merchant.bean.ShopStore;
import com.yaolaizaixian.merchant.order.InformationServiceActivity;
import com.yaolaizaixian.merchant.spinner.NiceSpinner;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/2/23.
 */
public class Fragment_home extends Fragment {

    private static final String TAG = "Fragment_home";
    @BindView(R.id.ll_home)
    AutoRelativeLayout llHome;
    @BindView(R.id.iv_yanzheng)
    ImageView ivYanzheng;
    @BindView(R.id.iv_jiezhang)
    ImageView ivJiezhang;
    private HomeActivity homeActivity;
    private List<ShopData> employeeStoreRealtionList;
    //商户ID
    private String employeeSysno;
    private int shopsysno = 0;
    private NiceSpinner nice;
    private List<String> shopnames;
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);

                    if (baseModel.isFlag()) {

                        final ShopListModel shopListModel = GsonUtil.jsonToBean(result, ShopListModel.class);
                        employeeStoreRealtionList = shopListModel.getData().getEmployeeStoreRealtionList();
                        if (employeeStoreRealtionList.size() > 0) {
                            //设置数据
                            for (int i = 0; i < employeeStoreRealtionList.size(); i++) {

//                                if (!TextUtils.isEmpty(shopvendor)){
//                                    adapter.add(shopvendor+"—"+employeeStoreRealtionList.get(i).getStorename());
//                                }else {
//                                    adapter.add(employeeStoreRealtionList.get(i).getStorename());
//                                }
                                shopnames.add(employeeStoreRealtionList.get(i).getVendorName() + "—" + employeeStoreRealtionList.get(i).getStorename());
                                //判断登录保存的商品id一样的
                                if (employeeStoreRealtionList.get(i).getSysno().equals(SharedPreferencesUtil.getString(getActivity(), "shopsysno", ""))) {
                                    shopsysno = i;
                                }

                            }

                        } else {

                            shopsysno = 0;
                            shopnames.add(shopvendor+"-"+shopName);
                        }


                        nice.attachDataSource(shopnames);
                        nice.setSelectedIndex(shopsysno);
                        nice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                                //店铺id
                                getDetail(employeeStoreRealtionList.get(position).getSysno());
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });


                    } else {

                        //店铺列表为null时从登陆中获取
                        shopsysno = 0;
                        shopnames.add(shopvendor+"-"+shopName);

                        nice.attachDataSource(shopnames);
                        nice.setSelectedIndex(shopsysno);
                        nice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                                //店铺id
                                getDetail(employeeStoreRealtionList.get(position).getSysno());
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            HomeActivity activity = (HomeActivity) getActivity();
                            activity.showConflictDialog("账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {


                            HomeActivity activity = (HomeActivity) getActivity();
                            activity.showConflictDialog("您的账号在其它设备登录");

                        } else {

                          //  Toasty.error(getActivity(), "请求失败", Toast.LENGTH_SHORT, true).show();
                            Log.e(TAG, baseModel.getErrorMsg());
                            return;
                        }

                    }

                    break;

                case 2:

                    String result2 = (String) msg.obj;

                    LogUtil.LogShitou(TAG, result2);

                    BaseModel baseModel2 = GsonUtil.jsonToBean(result2, BaseModel.class);

                    if (baseModel2.isFlag()) {

                        final ShopDetailsModel shopDetailsModel = GsonUtil.jsonToBean(result2, ShopDetailsModel.class);
                        ShopStore shopStore = shopDetailsModel.getData().getShopStore();

                        //店铺地址
                        SharedPreferencesUtil.saveString(getActivity(), "shopAddress", shopStore.getAddress());
                        //店铺image
                        SharedPreferencesUtil.saveString(getActivity(), "shopImage", shopStore.getStorelogoimage());
                        //保存店鋪名称
                        SharedPreferencesUtil.saveString(getActivity(), "Shopname", shopStore.getStorename());
                        //店铺id
                        SharedPreferencesUtil.saveString(getActivity(), "shopsysno", shopStore.getSysno());
                        HomeActivity activity = (HomeActivity) getActivity();
                        activity.getLeftMenuFragment().changeImage();

                    } else {

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel2.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            HomeActivity activity = (HomeActivity) getActivity();
                            activity.showConflictDialog("账号被停用");

                        } else if (baseModel2.getErrorCode().equals(BaseInfo.LogOutCode1)) {


                            HomeActivity activity = (HomeActivity) getActivity();
                            activity.showConflictDialog("您的账号在其它设备登录");

                        } else {
                            Toasty.error(getActivity(), "选择失败", Toast.LENGTH_SHORT, true).show();
                            Log.e(TAG, baseModel2.getErrorMsg());
                            return;
                        }

                    }
                    break;

            }
        }
    };

    //标记第一次选择
    private boolean isFlag = true;
    private String shopvendor;
    private String shopName;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);
        homeActivity = (HomeActivity) getActivity();
        shopnames = new ArrayList<>();
        nice = (NiceSpinner) view.findViewById(R.id.nice);
        ButterKnife.bind(this, view);
        //获取员工id
        employeeSysno = SharedPreferencesUtil.getString(getActivity(), "usersysno", "");
        //商户名
        shopvendor = SharedPreferencesUtil.getString(getActivity(), "shopvendor", "");
        if (!TextUtils.isEmpty(SharedPreferencesUtil.getString(getActivity(), "shopvendor", ""))&&shopvendor.length()>10){
            shopvendor=shopvendor.substring(0,9)+"...";
        }
        //店铺名
        shopName = SharedPreferencesUtil.getString(getActivity(), "Shopname", "");
        if (!TextUtils.isEmpty(SharedPreferencesUtil.getString(getActivity(), "Shopname", ""))&&shopName.length()>10){
            shopName=shopName.substring(0,9)+"...";
        }

 /*       //未展开的样式
        adapter = new ArrayAdapter<String>(getActivity(),
                R.layout.spinner_top, R.id.tv_shopname);*/
        //展开后的样式
        // adapter.setDropDownViewResource(R.layout.spinner_down);
        getData();

        return view;
    }

    @OnClick({R.id.iv_yanzheng, R.id.iv_jiezhang})
    public void onClick(View view) {
        switch (view.getId()) {


            case R.id.iv_yanzheng:

                // 1是会员验证
                Intent intent = new Intent(getActivity(), InformationServiceActivity.class);
                intent.putExtra("type", "1");
                startActivity(intent);
                break;

            // 2是结账
            case R.id.iv_jiezhang:

                /*Intent intent1 = new Intent(getActivity(), InformationServiceActivity.class);
                intent1.putExtra("type", "2");
                startActivity(intent1);*/


                Intent intent1 = new Intent(getActivity(), CreateOrderActivity.class);
                startActivity(intent1);



                break;
        }
    }

    //店铺列表
    private void getData() {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();

            final String url = BaseInfo.URL + "shopping/shoppingListInfo.do";
            // sysNo 值  3des加密
            //商户ID
            sortedParams.put("employeeSysno", employeeSysno);

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getActivity()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            //Toasty.error(getActivity(), "请检查网络", Toast.LENGTH_SHORT, true).show();
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

    //店铺详情
    private void getDetail(String shopStoreSysno) {

        try {
            final String url = BaseInfo.URL + "shopping/shoppingInfo.do";
            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            sortedParams.put("shopStoreSysno", shopStoreSysno);
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getActivity()))
                    .build()
                    .execute(new MyStringCallback2());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class MyStringCallback2 extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            Toasty.error(getActivity(), "请检查网络", Toast.LENGTH_SHORT, true).show();
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 2;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

}
